import { Controller, Get, Post, Body, Param, Put, Delete, Req, Res, QueryParams } from 'routing-controllers';
import { Container } from 'typedi';
import { RoleService } from '@services/role.service';
import { CreateRoleDto, RolePageDto, UpdateRoleDto } from '@/dtos';
import { Log, LogOperation } from '@decorators/logs.decorators';
import { ApiResponseBuilder } from '@utils/api-response-builder';
import { RequestWithUser } from '@/interfaces';
import { Request, Response } from 'express';
import { OpenAPI } from 'routing-controllers-openapi';
import { RequiredPerm } from '@decorators/perm.decorator';

@Controller('/roles')
export class RoleController {
  private role = Container.get(RoleService);

  @Get('/page')
  @RequiredPerm('roles:page')
  @OpenAPI({ summary: '获取角色分页列表' })
  async findAll(@QueryParams() pageDto: RolePageDto, @Req() req: Request, @Res() res: Response) {
    const { list, total } = await this.role.findAll(pageDto);
    return new ApiResponseBuilder(req, res).paginate(list, total, pageDto.pageNum || 1, pageDto.pageSize || 20);
  }

  @Get('/detail/:code')
  @RequiredPerm('roles:detail')
  @OpenAPI({ summary: '获取角色详情' })
  async findOne(@Param('code') code: string, @Req() req: Request, @Res() res: Response) {
    const result = await this.role.findOne(code);
    return new ApiResponseBuilder(req, res).success(result);
  }

  @Post('/create')
  @RequiredPerm('roles:create')
  @OpenAPI({ summary: '创建角色' })
  @Log({ bizType: 'role', operation: LogOperation.CREATE, bizId: (req: { user: { id: string } }) => `role:create:${req?.user?.id ?? ''}` })
  async create(@Body() dto: CreateRoleDto, @Req() req: RequestWithUser, @Res() res: Response) {
    await this.role.create(dto);
    return new ApiResponseBuilder(req, res).success();
  }

  @Put('/update/:code')
  @RequiredPerm('roles:update')
  @OpenAPI({ summary: '更新角色' })
  @Log({ bizType: 'role', operation: LogOperation.UPDATE, bizId: (req: { user: { id: string } }) => `role:update:${req?.user?.id ?? ''}` })
  async update(@Param('code') code: string, @Body() dto: UpdateRoleDto, @Req() req: RequestWithUser, @Res() res: Response) {
    await this.role.update(code, dto);
    return new ApiResponseBuilder(req, res).success();
  }

  @Delete('/delete/:code')
  @RequiredPerm('roles:delete')
  @OpenAPI({ summary: '删除角色' })
  @Log({ bizType: 'role', operation: LogOperation.DELETE, bizId: (req: { user: { id: string } }) => `role:delete:${req?.user?.id ?? ''}` })
  async remove(@Param('code') code: string, @Req() req: RequestWithUser, @Res() res: Response) {
    await this.role.remove(code);
    return new ApiResponseBuilder(req, res).success();
  }
}
